package com.hu.gulimallproduct.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hu.gulimallcommon.constant.ProductConstant;
import com.hu.gulimallcommon.utils.PageUtils;
import com.hu.gulimallcommon.utils.Query;
import com.hu.gulimallproduct.project.dao.PmsAttrAttrgroupRelationDao;
import com.hu.gulimallproduct.project.dao.PmsAttrDao;
import com.hu.gulimallproduct.project.dao.PmsAttrGroupDao;
import com.hu.gulimallproduct.project.dao.PmsCategoryDao;
import com.hu.gulimallproduct.project.entity.PmsAttrAttrgroupRelationEntity;
import com.hu.gulimallproduct.project.entity.PmsAttrEntity;
import com.hu.gulimallproduct.project.entity.PmsAttrGroupEntity;
import com.hu.gulimallproduct.project.entity.PmsCategoryEntity;
import com.hu.gulimallproduct.project.service.PmsAttrService;
import com.hu.gulimallproduct.project.service.PmsCategoryService;
import com.hu.gulimallproduct.project.vo.PmsAttrRespVO;
import com.hu.gulimallproduct.project.vo.PmsAttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service()
public class PmsAttrServiceImpl extends ServiceImpl<PmsAttrDao, PmsAttrEntity> implements PmsAttrService {
    @Autowired
    PmsAttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    PmsCategoryDao categoryDao;
    @Autowired
    PmsAttrGroupDao attrGroupDao;
    @Autowired
    PmsCategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),
                new QueryWrapper<PmsAttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDetail(PmsAttrVO pmsAttr) {
        //保存基础数据
        PmsAttrEntity entity = new PmsAttrEntity();
        BeanUtils.copyProperties(pmsAttr,entity);
        this.save(entity);
        //保存关联关系，使用了mybatisplus的回填机制所以获取到了新增的id
        if(pmsAttr.getAttrGroupId()!=null){
            PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelation = new PmsAttrAttrgroupRelationEntity();
            pmsAttrAttrgroupRelation.setAttrGroupId(pmsAttr.getAttrGroupId());
            pmsAttrAttrgroupRelation.setAttrId(entity.getAttrId());
            attrAttrgroupRelationDao.insert(pmsAttrAttrgroupRelation);
        }
    }


    @Override
    public void updateDetail(PmsAttrVO pmsAttr) {
        //修改基础数据
        PmsAttrEntity entity = new PmsAttrEntity();
        BeanUtils.copyProperties(pmsAttr,entity);
        this.updateById(entity);
        if(pmsAttr.getAttrType().equals(ProductConstant.AttrEnum.BASE_ATTR.getCode())){
            //保存关联关系，使用了mybatisplus的回填机制所以获取到了新增的id
            PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelation = new PmsAttrAttrgroupRelationEntity();
            pmsAttrAttrgroupRelation.setAttrGroupId(pmsAttr.getAttrGroupId());
            pmsAttrAttrgroupRelation.setAttrId(entity.getAttrId());
            Long attrId = attrAttrgroupRelationDao.selectCount(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", entity.getAttrId()));
            if(attrId>0){
                attrAttrgroupRelationDao.update(pmsAttrAttrgroupRelation,new UpdateWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id",entity.getAttrId()));
            }else {
                attrAttrgroupRelationDao.insert(pmsAttrAttrgroupRelation);
            }
        }
    }

    @Override
    public PmsAttrRespVO getInfo(Long attrId) {
        PmsAttrRespVO respVO = new PmsAttrRespVO();
        PmsAttrEntity byId = this.getById(attrId);
        BeanUtils.copyProperties(byId,respVO);
        PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", byId.getAttrId()));
        if(pmsAttrAttrgroupRelation!= null){
            respVO.setAttrGroupId(pmsAttrAttrgroupRelation.getAttrGroupId());
            PmsAttrGroupEntity pmsAttrGroupEntity = attrGroupDao.selectById(pmsAttrAttrgroupRelation.getAttrGroupId());
            if(pmsAttrGroupEntity!=null){
                respVO.setGroupName(pmsAttrGroupEntity.getAttrGroupName());
            }

        }
        Long[] longs = categoryService.selectCatelogPath(byId.getCatelogId());
        respVO.setCatelogPath(longs);
        PmsCategoryEntity pmsCategoryEntity = categoryDao.selectById(byId.getCatelogId());
        if(pmsCategoryEntity!=null){
            respVO.setCatelogName(pmsCategoryEntity.getName());
        }
        return respVO;
    }

    @Override
    public List<PmsAttrEntity> listRelationAttr(Long attrGroupId) {
        List<PmsAttrAttrgroupRelationEntity> attrgroupRelationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> collect = attrgroupRelationEntities.stream().map((x) -> {
            return x.getAttrId();
        }).collect(Collectors.toList());
        List<PmsAttrEntity> pmsAttrEntities = null;
        if(attrgroupRelationEntities.size()>0){
            pmsAttrEntities = this.listByIds(collect);
        }
        return pmsAttrEntities;
    }

    @Override
    public PageUtils pageRelationNoAttr(Long attrGroupId, Map<String, Object> params) {
        //1.当前分组只能关联自己所属的分类里面的所有属性
        PmsAttrGroupEntity pmsAttrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = pmsAttrGroupEntity.getCatelogId();
        //2.当前分组只能关联自己和别的分组没有引用的属性
        List<PmsAttrGroupEntity> groupIds = attrGroupDao.selectList(new QueryWrapper<PmsAttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> attrGroup = groupIds.stream().map(x -> {
            return x.getAttrGroupId();
        }).collect(Collectors.toList());

        List<PmsAttrAttrgroupRelationEntity> attrGroupIds = attrAttrgroupRelationDao.selectList(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().in("attr_group_id", attrGroup));
        //3.移除不能关联的属性
        List<Long> collect = attrGroupIds.stream().map(x -> {
            return x.getAttrId();
        }).collect(Collectors.toList());

        QueryWrapper<PmsAttrEntity> queryWrapper = new QueryWrapper<PmsAttrEntity>()
                .eq("catelog_id", catelogId);
//                .eq("attr_type",ProductConstant.AttrEnum.BASE_ATTR.getCode());
        if(collect!=null && collect.size()>0){
            queryWrapper.notIn("attr_id", collect);
        }
        String key =(String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
            });
        }
        IPage<PmsAttrEntity> page = this.page(new Query<PmsAttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    @Override
    public PageUtils baseList(Long catelogId, String attrType, Map<String, Object> params) {
        QueryWrapper<PmsAttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type","base".equals(attrType)? ProductConstant.AttrEnum.BASE_ATTR.getCode() :ProductConstant.AttrEnum.SALE_ATTR.getCode());
        if(catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        String key =(String) params.get("key");
        if(StringUtils.isNotEmpty(key)){
            queryWrapper.and((obj)->{
                obj.eq("attr_id",key)
                        .or()
                        .like("attr_name",key);
            });
        }
        IPage<PmsAttrEntity> page = this.page(
                new Query<PmsAttrEntity>().getPage(params),queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<PmsAttrEntity> records = page.getRecords();

        List<PmsAttrRespVO> collect = records.stream().map((attrEntity) -> {
            PmsAttrRespVO attrRespVO = new PmsAttrRespVO();
            BeanUtils.copyProperties(attrEntity,attrRespVO);
            if("base".equals(attrType)){
                //设置属性名称
                PmsAttrAttrgroupRelationEntity pmsAttrAttrgroupRelation = attrAttrgroupRelationDao.selectOne(new QueryWrapper<PmsAttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                if(pmsAttrAttrgroupRelation !=null){
                    PmsAttrGroupEntity pmsAttrGroupEntity = attrGroupDao.selectById(pmsAttrAttrgroupRelation.getAttrGroupId());
                    attrRespVO.setGroupName(pmsAttrGroupEntity.getAttrGroupName());
                }
            }
            //设置分组名称
            PmsCategoryEntity pmsCategoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            attrRespVO.setCatelogName(pmsCategoryEntity.getName());
            return attrRespVO;
        }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

}